﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using System.Threading;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.Json;
using System.Text;
using System.IO;

namespace FlickrWP7
{
    public partial class MainPage : PhoneApplicationPage
    {
        byte[] buffer;

        public MainPage()
        {
            InitializeComponent();
            //IsolatedStorageFile.GetUserStoreForApplication().DeleteFile("profile");
            txtUser.Text = "Hey, " + System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["user"].ToString() + "!";

            if (IsolatedStorageFile.GetUserStoreForApplication().FileExists("profile"))
            {
                LoadLocalProfile();
            }
            else
            {
                LoadWebProfile();
            }

            

            Debug.WriteLine(IsolatedStorageFile.GetUserStoreForApplication().FileExists("icon.jpg").ToString());
            //SetImage();
        }

        private void SetProfileData()
        {
            string contents = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

            JsonObject json = JsonObject.Parse(contents) as JsonObject;
            JsonValue value = null;

            json.TryGetValue("person", out value);
            json = JsonObject.Parse(value.ToString()) as JsonObject;

            JsonObject count = json;
            JsonValue counter = null;
            count.TryGetValue("photos", out counter);
            count = JsonObject.Parse(counter.ToString()) as JsonObject;
            count.TryGetValue("count", out counter);
            count = JsonObject.Parse(counter.ToString()) as JsonObject;
            count.TryGetValue("_content", out counter);
            txtUploads.Text = counter.ToString();

            json.TryGetValue("ispro", out value);
            if (value.ToString() == "0")
            {
                txtIsPro.Text = "NO";
                txtIsPro.Foreground = new SolidColorBrush(Colors.Red);
            }
            else
            {
                txtIsPro.Text = "YES";
                txtIsPro.Foreground = new SolidColorBrush(Colors.Green);
            }

            json.TryGetValue("realname", out value);
            json = JsonObject.Parse(value.ToString()) as JsonObject;
            json.TryGetValue("_content", out value);

            string realName = value.ToString().Remove(0, 1);
            realName = realName.Remove(realName.Length - 1, 1);
            txtRealName.Text = realName;

            SetImage();
        }

        private void SetImage()
        {
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            
            using (IsolatedStorageFileStream stream = file.OpenFile("icon.jpg",FileMode.Open))
            {
                buffer = new byte[stream.Length];
                stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ImageReadCompleted), stream);
            }
        }

        void ImageReadCompleted(IAsyncResult result)
        {
            IsolatedStorageFileStream stream = (IsolatedStorageFileStream)result.AsyncState;
            stream.EndRead(result);

            MemoryStream mStream = new MemoryStream(buffer);
            BitmapImage image = new BitmapImage();
            image.SetSource(mStream);

            profileImage.Source = image;
        }

        void LoadLocalProfile()
        {
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("profile", System.IO.FileMode.Open, file))
            {
                buffer = new byte[stream.Length];
                stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ReadCompleted), stream);
            }
        }

        void ReadCompleted(IAsyncResult result)
        {
            IsolatedStorageFileStream stream = (IsolatedStorageFileStream)result.AsyncState;
            stream.EndRead(result);

            SetProfileData();
        }

        void LoadWebProfile()
        {
            Core.People people = new Core.People();
            people.GetInfo(App.API_KEY, IsolatedStorageSettings.ApplicationSettings["id"].ToString(), () =>
            {
                JsonObject json = JsonObject.Parse(Core.Json.MakeValidJson(people.PeopleQueryResult)) as JsonObject;

                SaveProfileData(json);
                SaveImage(json);
            });
        }

        void SaveImage(JsonObject json)
        {
            JsonValue value = null;
            json.TryGetValue("person", out value);
            json = JsonObject.Parse(value.ToString()) as JsonObject;
            json.TryGetValue("iconserver", out value);

            string iconServer = value.ToString().Remove(0, 1);
            iconServer = iconServer.Remove(iconServer.Length - 1, 1);

            json.TryGetValue("iconfarm", out value);

            string iconFarm = value.ToString();

            string buddyIconUrl = string.Format("http://farm{0}.static.flickr.com/{1}/buddyicons/{2}.jpg",
                iconFarm, iconServer, IsolatedStorageSettings.ApplicationSettings["id"].ToString());

            WebClient client = new WebClient();
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            client.OpenReadAsync(new Uri(buddyIconUrl));
        }

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            byte[] image = Core.ByteConverter.ConvertToByte(e.Result);

            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("icon.jpg", System.IO.FileMode.Create, file))
            {
                stream.BeginWrite(image, 0, image.Length, new AsyncCallback(EndImageWrite), stream);
            }
        }

        void EndImageWrite(IAsyncResult result)
        {
            IsolatedStorageFileStream stream = (IsolatedStorageFileStream)result.AsyncState;
            stream.EndWrite(result);
            stream.Close();

            LoadLocalProfile();
        }

        void SaveProfileData(JsonObject json)
        {
            buffer = Encoding.UTF8.GetBytes(json.ToString());

            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("profile", System.IO.FileMode.OpenOrCreate, file))
            {
                stream.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(EndProfileWrite), stream); 
            }
        }

        void EndProfileWrite(IAsyncResult result)
        {
            IsolatedStorageFileStream stream = (IsolatedStorageFileStream)result.AsyncState;
            stream.EndWrite(result);
            stream.Close();
        }

    }
}